<template>
	<view class="dashboard-container">
		<!-- 图表容器 -->
		<view class="chart-container">
			<view class="chart-title">近三个月订单趋势</view>
			<canvas canvas-id="orderChart" id="orderChart" class="charts" :style="{ 
          width: chartWidth + 'px', 
          height: chartHeight + 'px',
          position: 'relative',  // 关键样式修复
          zIndex: 0 
        }"></canvas>
		</view>

		<view class="chart-container">
			<view class="chart-title">近三个月金额趋势</view>
			<canvas canvas-id="amountChart" id="amountChart" class="charts" :style="{ 
          width: chartWidth + 'px', 
          height: chartHeight + 'px',
          position: 'relative',
          zIndex: 0
        }"></canvas>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		getCurrentInstance
	} from 'vue';
	import uCharts from '@qiun/ucharts';

	const instance = getCurrentInstance(); // 获取组件实例
	const chartWidth = ref(300);
	const chartHeight = ref(200);

	// 初始化图表
	const initChart = (canvasId, chartData) => {
		const query = uni.createSelectorQuery().in(instance);
		query.select('#' + canvasId)
			.fields({
				node: true,
				size: true
			})
			.exec(res => {
				if (!res[0]) {
					console.error('Canvas节点未找到');
					return;
				}

				const canvas = res[0].node;
				const ctx = canvas.getContext('2d');
				const dpr = uni.getSystemInfoSync().pixelRatio;

				// 适配高清屏
				canvas.width = res[0].width * dpr;
				canvas.height = res[0].height * dpr;
				ctx.scale(dpr, dpr);

				new uCharts({
					context: ctx, // 关键参数
					canvasId: canvasId,
					type: 'column',
					width: res[0].width,
					height: res[0].height,
					categories: chartData.categories,
					series: chartData.series,
					dataLabel: true,
					yAxis: {
						format: chartData.format
					},
					extra: {
						column: {
							width: chartWidth.value * 0.45 / chartData.categories.length
						}
					}
				});
			});
	};

	// 数据准备
	const prepareData = () => ({
		orderData: {
			categories: ['2025-04', '2025-05', '2025-06'],
			series: [{
				data: [3, 8, 5],
				format: val => `${val} 单`
			}]
		},
		amountData: {
			categories: ['2025-04', '2025-05', '2025-06'],
			series: [{
				data: [49, 128, 65],
				format: val => `¥${val.toFixed(2)}`
			}]
		}
	});

	onMounted(() => {
		// 动态计算尺寸
		const systemInfo = uni.getSystemInfoSync();
		chartWidth.value = systemInfo.windowWidth * 0.9;
		chartHeight.value = chartWidth.value * 0.67;

		// 延迟确保渲染完成
		setTimeout(() => {
			const {
				orderData,
				amountData
			} = prepareData();
			initChart('orderChart', orderData);
			initChart('amountChart', amountData);
		}, 500);
	});
</script>

<style lang="scss" scoped>
	.chart-container {
		margin: 20rpx;
		padding: 20rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

		.chart-title {
			font-size: 32rpx;
			color: #333;
			padding-bottom: 20rpx;
		}
	}

	.charts {
		// 关键样式修复
		display: block;
		box-sizing: border-box;
	}
</style>